import React, { Component } from 'react';
import { NavLink, withRouter } from 'react-router-dom';
import { getResouliebiao } from '../../utils/api';
import './Header.css';

class Header extends Component {
	state = {
		reshouliebiao: [],
		keyWords: '',
		display: 'none'
	}
	componentDidMount () {
		this.getResouliebiaos();
	}
	async getResouliebiaos () {
		const reshouliebiao = await getResouliebiao();
		this.setState({
			reshouliebiao: reshouliebiao.result.hots
		})
	}
	getKeyWords = (e) => {
		if (e.target.value.trim().length === 0 && e.keyCode === 13) {
			alert('请重新输入，不能输入为空的关键词');
			e.target.value = '';
			this.setState({
				keyWords: ''
			})
		} else if (e.keyCode === 13) {
			this.setState({
				keyWords: e.target.value.trim(),
				display: 'none'
			}, function () {
				this.props.history.push(`/search?keywords=${this.state.keyWords}&type=1`);
			})
		}
	}
	goSearch (keywords) {
		this.setState({ display: 'none' });
		this.props.history.push(`/search?keywords=${keywords}&type=1`);
	}
	render () {
		let { reshouliebiao, display } = this.state;
		return (
			<div className='header_box'>
				<div className='header'>
					<ul className='list'>
						<li>
							<NavLink activeClassName='active' to='/faxianmusic'>发现音乐</NavLink>
						</li>
						<li>
							<NavLink activeClassName='active' to='/tuijiangedan'>推荐歌单</NavLink>
						</li>
						<li>
							<NavLink activeClassName='active' to='/zuixinsong'>最新歌曲</NavLink>
						</li>
						<li>
							<NavLink activeClassName='active' to='/zuixinmv'>推荐MV</NavLink>
						</li>
						<li>
							<NavLink activeClassName='active' to='/remengeshou'>热门歌手(Top25)</NavLink>
						</li>
						<li>
							<NavLink activeClassName='active' to='/paihang'>排行榜</NavLink>
						</li>
					</ul>
					<div className='search_box'>
						<input onFocus={() => { this.setState({ display: 'block' }) }} placeholder='请输入关键词,按回车键搜索' type="text" onKeyUp={this.getKeyWords} name="" id="" />
						<ul className='hotkeywords' style={{ display: display }}>
							<li>热门搜索  <span style={{ marginLeft: '100px', cursor: 'pointer' }} onClick={() => { this.setState({ display: 'none' }) }}>关闭</span></li>
							{reshouliebiao.map((item, index) => (
								<li key={index} onClick={() => { this.goSearch(item.first) }} className='red'>{item.first}</li>
							))}
						</ul>
					</div>
				</div>
			</div>
		)
	}
}

export default withRouter(Header);

